<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="success" @click="exportExcel">导出</el-button>

        <el-button style="float:right; margin-right: 15px" @click="uploadExcel()">上传</el-button>

        <el-button style="float:right; margin-right: 30px" type="primary" @click="getTowersList()">查询</el-button>
        <el-button style="float:right; margin-right: 15px" @click="handleResetSearch()">重置</el-button>
      </div>
      <!-- 文件上传窗口 -->
      <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
          <el-upload class="upload-demo" drag action="" :show-file-list="false" :before-upload="handleBeforeUpload"
            :on-change="handleFileChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖拽文件(.xlsx)到此区域进行上传</div>
          </el-upload>
          <el-table :data="uploadedData" v-if="uploadedData.length">
            <el-table-column prop="站点名" label="站点名" />
            <el-table-column prop="站点编号" label="站点编号" />
            <el-table-column prop="经度" label="经度" />
            <el-table-column prop="监测时间" label="监测时间" />
            <el-table-column prop="CO浓度" label="CO浓度" />    
            <el-table-column prop="NO2浓度" label="NO2浓度" /> 
            <el-table-column prop="臭氧浓度" label="臭氧浓度" /> 
            <el-table-column prop="SO2浓度" label="SO2浓度" />  
          </el-table>
          <template #footer>
            <el-button @click="uploadData">上传</el-button>
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
          </template>
        </el-dialog>
      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <div style="display: inline-block;margin-left:5px">
            <el-form-item label="站点名：">
              <el-input class="input-width" placeholder="站点名" v-model="queryParams.param.PointName"
                clearable></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:5px">
            <el-form-item label="站点编号:">
              <el-input class="input-width" placeholder="站点编号" v-model="queryParams.param.StationCode"
                clearable></el-input>
            </el-form-item>
          </div>
          <div class="block" style="display: inline-block;margin-left:20px">
            <span class="demonstration">选择时间段 ：</span>
            <el-date-picker
              v-model="value1"
              type="datetimerange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
        </el-form>
      </div>
    </el-card>

    <el-table ref="multipleTableRef" :data="towersList" empty-text="正在加载" style="width:100%" :broder="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="pointName" label="站点名" />
      <el-table-column prop="stationCode" label="站点编号" />
      <el-table-column prop="longitude" label="经度" />
      <el-table-column prop="latitude" label="海拔" />
      <el-table-column prop="time" label="监测时间" width="200" />
      <el-table-column prop="co" label="CO浓度" />
      <el-table-column prop="no2" label="NO2浓度" />
      <el-table-column prop="o3" label="臭氧浓度" />
      <el-table-column prop="so2" label="SO2浓度" />
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div>
      <el-pagination :current-page="queryParams.pageNum" 
      :page-size="queryParams.pageSize" 
      :page-sizes="[15, 30, 45]"
      :small="false" :disabled="false" 
      :background="true" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleNumChange" />
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="修改信息" width="800">
      <el-form ref="formRef" :model="updateForm" :rules="rules">
        <el-form-item prop="longitude" label="经度：">
          <el-input v-model="updateForm.longitude" />
        </el-form-item>
        <el-form-item prop="latitude" label="海拔：">
          <el-input v-model="updateForm.latitude" />
        </el-form-item>
        <el-form-item prop="co" label="CO：">
          <el-input v-model="updateForm.co" />
        </el-form-item>
        <el-form-item prop="no2" label="NO2：">
          <el-input v-model="updateForm.no2" />
        </el-form-item>
        <el-form-item prop="o3" label="O3：">
          <el-input v-model="updateForm.o3" />
        </el-form-item>
        <el-form-item prop="so2" label="SO2：">
          <el-input v-model="updateForm.so2" />
        </el-form-item>
        <el-form-item prop="stationCode" label="站点编号：">
          <el-input v-model="updateForm.stationCode" />
        </el-form-item>
        <el-form-item prop="pointName" label="站点名：">
          <el-input v-model="updateForm.pointName" />
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { deleteTower, fetchTowersByPage, updateTower ,uploadTower} from "../../../api/towerApi";
import { nextTick, ref, reactive, onMounted, VueElement } from "vue";
import { ElMessage, ElMessageBox, } from "element-plus";
import * as XLSX from "xlsx";



const value1 = ref<[Date | null, Date | null]>([null, null]);
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  param: {
    PointName: "",
    StationCode: "",
    earliestTime: "",
    latestTime: ""
  }
});

const towersList = ref([]); // 直接使用 ref 定义数组
let total = ref(0);

function getTowersList() {

  queryParams.param.earliestTime = value1.value[0]?.toLocaleString() || '';
  queryParams.param.latestTime = value1.value[1]?.toLocaleString() || '';


  fetchTowersByPage(queryParams)
    .then(res => {

      // 确保从 res 中提取数组
      towersList.value = res.data.result.records; // 如果 res 是数组
      // 或者根据实际情况调整，如：towersList.value = res.data;
      total.value = res.data.result.total;

      //queryParams.param.PointName = 

    })
    .catch(error => {
      console.error("Error fetching towers list:", error);
    });
}



//重置事件
const handleResetSearch = async () => {
  queryParams.param.PointName = '',
  queryParams.param.StationCode = '',
  queryParams.param.earliestTime='',
  queryParams.param.latestTime='',
  value1.value = [null, null],
  getTowersList()

}

const handleSizeChange = val => {
  queryParams.pageSize = val;
  getTowersList();
};

const handleNumChange = val => {
  queryParams.pageNum = val;
  getTowersList();
};

//编辑功能
const dialogFormVisible = ref(false);
const formRef = ref();

const updateForm = ref({
  longitude: "",
  latitude: "",
  time: "",
  co: "",
  no2: "",
  o3: "",
  so2: "",
  stationCode: "",
  pointName: ""
});

const handleEdit = (rowData = {}) => {
  dialogFormVisible.value = true;

  //弹窗打开form 声称是异步的
  nextTick(() => {
    //如果是编辑
    if (rowData) {
      Object.assign(updateForm.value, rowData);
      // updateForm.value = rowData
      console.log("这里是获取编辑数据", rowData);
    }
  });
};

const confirm = async () => {
  //把updateForm.value给列表的第一列
  let res = await updateTower(updateForm.value);
  if (res.code == 20000) {
    ElMessage({
      message: "修改成功",
      type: "success",
      duration: 1000
    });
    getTowersList();
  } else {
    ElMessage({
      message: "修改失败",
      type: "error",
      duration: 1000
    });
  }
  dialogFormVisible.value = false;
};

//删除
const deleteItem = async (id) => {
  try {
    await ElMessageBox.confirm('是否要该条数据', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteTower(id);
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1000
    });
  } catch (error) {
    // Handle cancel or error
  }
  getTowersList();
};

onMounted(() => {
  getTowersList();
});

//上传文件
const fieldMapping = {
    "站点名" :"pointName",
    "站点编号" :"stationCode" ,
    "经度" : "longitude",
    "海拔" :"latitude",
    "监测时间":"time",
    "CO浓度": "co",
    "NO2浓度": "no2" ,
    "臭氧浓度" :"o3",
    "SO2浓度" : "so2",
}
const uploadedData = ref([])
const uploadDialogVisible = ref(false)
const convertedData = ref([])

function uploadExcel() {
  uploadDialogVisible.value = true;
}

const handleFileChange = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);

    // 在读取数据后，处理'监测时间'列并将其转换为UTC时间
    jsonData.forEach((row) => {
      if (row['监测时间']) {
        // 假设 '监测时间' 是字符串或者日期格式
        const localTime = new Date(row['监测时间']);
        
        // 获取年月日、小时、分钟和秒
        const year = localTime.getFullYear();
        const month = String(localTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，+1
        const day = String(localTime.getDate()).padStart(2, '0');
        const hours = String(localTime.getHours()).padStart(2, '0');
        const minutes = String(localTime.getMinutes()).padStart(2, '0');
        const seconds = String(localTime.getSeconds()).padStart(2, '0');
        
        // 将日期时间拼接成 'yyyy-mm-dd hh:mm:ss' 格式
        const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        
        // 将转换后的时间替换原来的时间
        row['监测时间'] = formattedTime;
      }
    })

    uploadedData.value = jsonData; // 将读取的数据保存到 uploadedData
  };

  reader.readAsArrayBuffer(file.raw);
};

const uploadData = async () => {
  let convertedData = convertFields(uploadedData)
  // 遍历 convertedData 数组，并将每个元素的 id 设置为 null
  convertedData.forEach(item => {
    item.id = 0;
  });
  console.log("convertedData",convertedData);
  uploadTower(convertedData)
    .then(response => {
      if(response.code===20000){
        console.log("上传成功", response.code);
        uploadedData.value = []; // 清空上传数据
        uploadDialogVisible.value = false; // 关闭弹窗
        ElMessage({
          message: "上传成功",
          type: "success",
          duration: 1000
        });
        getTowersList();
      } else {
        ElMessage({
          message: "上传失败",
          type: "error",
          duration: 1000
        })
      }
    })
    .catch(error => {
      console.error('上传失败', error);
      ElMessage({
        message: "修改失败",
        type: "error",
        duration: 1000
      });
      // 你可以通过 error.response 获取详细的失败信息（比如 status 或 message）
      if (error.response) {
        // 请求已发出，服务器响应了状态码，且响应体
        console.error('服务器返回错误:', error.response.data);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        console.error('没有收到响应:', error.request);
      } else {
        // 发生了一些其他错误
        console.error('请求错误:', error.message);
      }
    });
};

const convertFields = (data) => {
  console.log("datadatadatadata",data.value);
  return data.value.map(row => {
    let convertedRow = {};
    Object.keys(row).forEach(key => {
      const englishKey = fieldMapping[key];
      if (englishKey) {
        // 如果是检测时间字段（detectionTime），则转换为国际时间格式
        // if (englishKey === 'detectionTime') {
        //   convertedRow[englishKey] = formatTimestamp(row[key]); // 格式化时间戳
        // } else {
          convertedRow[englishKey] = row[key];
        // }
      }
    });
    return convertedRow;
  });
};

const formatTimestamp = (timestamp) => {
  const date = new Date(timestamp); // 将时间戳转换为 Date 对象
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const convertedDataWithFormattedTime = convertedData.value.map(row => {
  console.log("11111111",convertedData.value)
  return {
    ...row,
    detectionTime: formatTimestamp(row.detectionTime)
  };
});

const selectedItems = ref([]); // 直接使用 ref 定义数组

function handleSelectionChange(selected) {
      selectedItems.value = selected; // 更新选中的项
      // console.log(selectedItems.value);
}
//下载文件
function exportExcel() {
  // 准备数据
  const data = selectedItems.value;

  // 检查数据是否为空
  if (data.length === 0) {
    console.error("没有可导出的数据");
        ElMessage({
        message: "没有可导出的数据",
        type: "error",
        duration: 1000
      });
    return;
  }

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 导出
  XLSX.writeFile(workbook, "data.xlsx");
}
</script>
<style lang="less">
.el-form-item {
  margin-bottom: 20px;
  /* 控制每个表单项之间的间距 */
}

.el-form-item__label {
  width: 120px;
  /* 固定标签宽度，以确保整齐 */
  text-align: right;
  /* 标签右对齐 */
}

.el-input {
  width: 300px;
  /* 固定输入框宽度 */
}

// 选择器样式
.block {
  padding: 10px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
 // display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>